﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Q42.WinRT.Portable.Data;
using SpaceNeedle.SDK.Windows.Platform.Data;
using SpaceNeedle.SDK.Windows.Platform.Events;
using SpaceNeedle.SDK.WindowsPhone;
using SpaceNeedle.x6473.WindowsPhone.Common;
using SpaceNeedle.x6473.WindowsPhone.Models;
using SpaceNeedle.x6473.WindowsPhone.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;


namespace SpaceNeedle.x6473.WindowsPhone.ViewModels
{
    public class AppViewModel : ViewModelBase
    {
        public static AppViewModel Instance;

        public AppViewModel()
        {
            AppViewModel.Instance = this;
            
            this.Properties = new Properties();
            this.Cache = new Cache();

            this.Properties.CanLoadOnlineAppContent = true;
        }

        #region Services

        public async Task<AppContent> LoadAppContent()
        {
            return await AppViewModel.Instance.Cache.Get(CacheKeys.AppContent, () => Api.LoadAppContent());
        }

        public async Task<ObservableCollection<Phone>> LoadPhones()
        {
            return await AppViewModel.Instance.Cache.Get(CacheKeys.Phones, () => Api.LoadPhones());
        }

        public async Task<ObservableCollection<Alert>> LoadAlerts()
        {
            return await AppViewModel.Instance.Cache.Get(CacheKeys.Alerts, () => Api.LoadAlerts());
        }

        public async Task ClearAlerts()
        {
            AppViewModel.Instance.Properties.AlertsBeginDate = DateTime.Now;
            await AppViewModel.Instance.Cache.Delete(CacheKeys.Alerts);

            Tracking.SendEvent("Dados", "Alertas Apagados", "Lista de Alertas Apagada", 0);
        }

        public async Task<ObservableCollection<SpaceNeedle.x6473.WindowsPhone.Models.Request>> LoadRequests()
        {
            var requests = await AppViewModel.Instance.Cache.Get(CacheKeys.Requests, () => Api.LoadRequests());
            this.Properties.Requests = requests;

            return requests;
        }

        public async Task<ObservableCollection<RequestItem>> LoadAllRequests()
        {
            return await AppViewModel.Instance.Cache.Get(CacheKeys.AllRequests, () => Api.LoadAllRequests());
        }

        public async Task<ObservableCollection<RequestItem>> LoadUserRequests()
        {
            return await AppViewModel.Instance.Cache.Get(CacheKeys.UserRequests, () => Api.LoadUserRequests());
        }
        #endregion

        #region Data
        public Properties Properties { get; set; }

        public Cache Cache { get; set; }

        public bool IsStateRestored { get; set; }

        public bool IsAuthenticated
        {
            get
            {
                return this.Properties.Me != null;
            }
        }
        
        public SpaceNeedle.x6473.WindowsPhone.Models.Request GetRequestById(Guid requestId)
        {
            if(this.Properties.Requests == null)
            {
                return null;
            }

            return this.Properties.Requests.Where(x => x.Id == requestId).SingleOrDefault();
        }
        #endregion

        #region State Management
        public async Task SaveAppState()
        {
            try
            {
                string json = JsonConvert.SerializeObject(this.Properties);
                await AppServices.Current.StorageService.SaveLocalFileStringAsync("AppState.json", json);
            }
            catch { }
        }

        public async Task RestoreAppState()
        {
            try
            {
                string json = await AppServices.Current.StorageService.ReadLocalFileStringAsync("AppState.json");

                var props = JsonConvert.DeserializeObject<Properties>(json);

                if (props != null)
                {
                    this.Properties = props;
                    this.IsStateRestored = true;
                }
            }
            catch { }
        }

       
        #endregion

        public async Task IncrementExecutions()
        {
            this.Properties.ExecutionsCount++;
            await this.SaveAppState();
        }
    }
}